package com.example.markdownviewer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import io.noties.markwon.Markwon;
import io.noties.markwon.ext.latex.JLatexMathPlugin;
import io.noties.markwon.ext.tables.TablePlugin;
import io.noties.markwon.html.HtmlPlugin;
import io.noties.markwon.image.ImagesPlugin;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
import io.noties.markwon.syntax.Prism4jThemeDarkula;
import io.noties.markwon.syntax.SyntaxHighlightPlugin;
import io.noties.prism4j.Prism4j;
import io.noties.prism4j.annotations.PrismBundle;

@PrismBundle(include = {"java", "kotlin", "javascript", "css", "markup", "c", "python"}, grammarLocatorClassName = ".MyGrammarLocator")
public class MainActivity extends AppCompatActivity implements PluginSettingsDialog.PluginSettingsListener, RecentFilesDialog.RecentFileListener {

    private static final int REQUEST_PERMISSION_CODE = 1001;
    private TextView markdownView;
    private Markwon markwon;
    private ActivityResultLauncher<Intent> filePickerLauncher;
    private Uri currentFileUri;
    private RecentFilesManager recentFilesManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // 初始化视图
        markdownView = findViewById(R.id.markdownView);
        
        // 初始化最近文件管理器
        recentFilesManager = new RecentFilesManager(this);

        // 设置文件选择器
        filePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri uri = result.getData().getData();
                        if (uri != null) {
                            Toast.makeText(this, uri.toString(), Toast.LENGTH_LONG).show();
                            currentFileUri = uri;
                            loadMarkdownFromUri(uri);
                        }
                    }
                });

        // 处理从其他应用打开的文件
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            Uri data = intent.getData();

            if (Intent.ACTION_VIEW.equals(action) && data != null) {
                currentFileUri = data;
                loadMarkdownFromUri(data);
            }
        }
    }

    private void initMarkwon() {
        // 重置Markwon实例
        markwon = null;
        
        // 获取插件设置
        Map<String, Boolean> pluginSettings = PluginSettingsDialog.getPluginSettings(this);
        
        // 初始化Markwon构建器
        Markwon.Builder builder = Markwon.builder(this);
        
        // 根据设置添加插件
        if (pluginSettings.get(PluginSettingsDialog.KEY_HTML))
            builder.usePlugin(HtmlPlugin.create());

        
        if (pluginSettings.get(PluginSettingsDialog.KEY_IMAGES))
            builder.usePlugin(ImagesPlugin.create());

        
        if (pluginSettings.get(PluginSettingsDialog.KEY_TABLES))
            builder.usePlugin(TablePlugin.create(this));

        
        if (pluginSettings.get(PluginSettingsDialog.KEY_SYNTAX))
            builder.usePlugin(SyntaxHighlightPlugin.create(new Prism4j(new MyGrammarLocator()), Prism4jThemeDarkula.create()));

        
        if (pluginSettings.get(PluginSettingsDialog.KEY_INLINE))
            builder.usePlugin(MarkwonInlineParserPlugin.create());

        
        if (pluginSettings.get(PluginSettingsDialog.KEY_LATEX))
            builder.usePlugin(JLatexMathPlugin.create(markdownView.getTextSize(), latexBuilder -> {
                // ENABLE inlines
                latexBuilder.inlinesEnabled(true);
            }));

        
        // 构建Markwon实例
        markwon = builder.build();
    }

    private void openFilePicker() {
        if (checkStoragePermission()) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("*/*");
            String[] mimeTypes = {"text/markdown", "text/x-markdown"};
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            filePickerLauncher.launch(intent);
            initMarkwon();
        } else {
            requestStoragePermission();
        }
    }

    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            return true; // Android 11及以上使用作用域存储，不需要存储权限
        }
        return ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestStoragePermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_PERMISSION_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openFilePicker();
            } else {
                Toast.makeText(this, R.string.permission_denied, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void loadMarkdownFromUri(Uri uri) {
        initMarkwon();
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                String markdownText = readTextFromInputStream(inputStream);
                markwon.setMarkdown(markdownView, markdownText);

                // 设置标题为文件名
                String fileName = getFileNameFromUri(uri);
                if (getSupportActionBar() != null) {
                    getSupportActionBar().setTitle(fileName);
                }
                
                // 保存到最近文件列表
                recentFilesManager.addRecentFile(uri, fileName);
                Toast.makeText(this, R.string.file_saved, Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Toast.makeText(this, R.string.error_opening_file, Toast.LENGTH_SHORT).show();
        }
    }

    private String readTextFromInputStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line).append('\n');
        }
        reader.close();
        return stringBuilder.toString();
    }

    private String getFileNameFromUri(Uri uri) {
        String fileName = "未知文件";
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals("content")) {
            try {
                String[] projection = {"_display_name"};
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex("_display_name");
                    if (columnIndex != -1) {
                        fileName = cursor.getString(columnIndex);
                    }
                    cursor.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (scheme != null && scheme.equals("file")) {
            fileName = uri.getLastPathSegment();
        }
        return fileName;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_open) {
            openFilePicker();
            return true;
        }
        if (itemId == R.id.action_recent_files) {
            showRecentFilesDialog();
            return true;
        }
        if (itemId == R.id.action_plugin_settings) {
            showPluginSettingsDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示插件设置对话框
     */
    private void showPluginSettingsDialog() {
        PluginSettingsDialog dialog = new PluginSettingsDialog();
        dialog.show(getSupportFragmentManager(), "PluginSettingsDialog");
    }

    /**
     * 插件设置变更后的回调
     */
    @Override
    public void onPluginSettingsChanged() {
        // 重新初始化Markwon
        markwon = null;
        
        // 如果当前有打开的文件，重新加载
        if (currentFileUri != null) {
            loadMarkdownFromUri(currentFileUri);
        }
    }
    
    /**
     * 显示最近文件对话框
     */
    private void showRecentFilesDialog() {
        RecentFilesDialog dialog = new RecentFilesDialog();
        dialog.show(getSupportFragmentManager(), "RecentFilesDialog");
    }
    
    /**
     * 最近文件被选择的回调
     */
    @Override
    public void onRecentFileSelected(Uri fileUri) {
        if (fileUri != null) {
            currentFileUri = fileUri;
            loadMarkdownFromUri(fileUri);
        }
    }
    
    /**
     * 清除最近文件的回调
     */
    @Override
    public void onClearRecentFiles() {
        recentFilesManager.clearRecentFiles();
        Toast.makeText(this, R.string.no_recent_files, Toast.LENGTH_SHORT).show();
    }
}